import 'package:flutter/material.dart';
import '../../../services/messageUtil.dart';
import '../../../services/userServices.dart';
import '../../../services/httpsClient.dart';
import 'package:get/get.dart';

class LoginController extends GetxController {
  //TODO: Implement LoginController
  TextEditingController phoneController = TextEditingController();
  TextEditingController passController = TextEditingController();
  HttpsClient httpsClient = HttpsClient();
  bool isLoading = true; //请求防抖控制

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  // Future<MessageModel> doLogin() async {
  //   var response = await httpsClient.get(
  //     "v1/auth/login",
  //     params: {"phone": phoneController.text, "password": passController.text},
  //   );
  //   if (response != null) {
  //     if (response.data['code'] == 0) {
  //       Storage.setData("userinfo", response.data["data"]);

  //       return MessageModel(message: "登录成功", code: response.data['code']);
  //     }
  //     return MessageModel(
  //       message: response.data["message"],
  //       code: response.data['code'],
  //     );
  //   } else {
  //     return MessageModel(message: "网络异常", code: 1);
  //   }
  // }
  doLogin() async {
    if (isLoading) {
      isLoading = false;
      var response = await httpsClient.get(
        "v1/auth/login",
        params: {
          "phone": phoneController.text,
          "password": passController.text,
        },
      );
      if (response != null) {
        if (response.data['code'] == 0) {
          await UserServices.saveUserData(response.data["data"]);
          MessageUtil.showSuccess(
            message: "登录成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );
          Get.offAllNamed('/home');
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }

      isLoading = true;
    }
  }
}
